//
//  GameCenterManager.swift
//  aircraftBattle1
//
//  Created by 许洋 on 2024/5/20.
//

import Foundation
import GameKit
 
class GameCenterManager: NSObject, GKGameCenterControllerDelegate {
    static let shared = GameCenterManager()
    
    func authenticatePlayer(_ vc: UIViewController) {
        let player = GKLocalPlayer.local
        player.authenticateHandler = { (viewController, error) in
            if (player.isAuthenticated) {
                print("Game Center 认证成功")
                self.showAchievements(vc)
            } else {
                print("Game Center 认证失败")
            }
        }
    }
    
    func showAchievements(_ vc: UIViewController) {
        let gameCenterViewController = GKGameCenterViewController(leaderboardID: "com.smo.localRank", playerScope: GKLeaderboard.PlayerScope.global, timeScope: GKLeaderboard.TimeScope.today)
        gameCenterViewController.gameCenterDelegate = self
        vc.present(gameCenterViewController, animated: true)
    }
    
    func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController) {
        gameCenterViewController.dismiss(animated: true)
    }
    func reportScore(score:Int) {
        if GKLocalPlayer.local.isAuthenticated {
            Task{
                try await GKLeaderboard.submitScore(
                    score,
                    context: 0,
                    player: GKLocalPlayer.local,
                    leaderboardIDs: ["com.smo.localRank"]
                )
            }
            print("Score submitted")
        }

    }

}
